/* eslint-disable array-callback-return */
import { GridList, GridListTile, Paper, Tooltip, Typography } from "@material-ui/core";
import TextField from "@material-ui/core/TextField";
import { Dialpad } from "@material-ui/icons";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { ms } from "milsymbol/index.esm";
import * as React from "react";
import Cookies from "universal-cookie";
import { searchSymbols } from "./milsymbolWrapper";
import * as symbolDict from "./ms2525cDict.json";

export interface IMilSymbolSearchProps {
  width?: number | string;
  iconSize?: number;
  cols?: number;
  onImgClick?:any;
}

export interface IMilSymbolSearchState {
  searchKeyword: string;
  mainIcons: [];
  currentSymbol:any;
}
export interface IFavMainIcon {
  sidc: string;
  label: string;
  count: number;
}

export const getSymbolBySidc = (sidc: string): string => {
  const symbol = new ms.Symbol(sidc, { size: 32 });
  let url;
  try {
    url = symbol.toDataURL();
  } catch (Error) {
    url =
      "data:image/svg+xml;base64," +
      window.btoa(unescape(encodeURIComponent(symbol.asSVG())));
  }
  return url;
};
export const MilSymbol = (sidc) => {
  const url = getSymbolBySidc(sidc);
  return <img src={url} width={32} height={32} alt="" />;
};

const cookies = new Cookies();

export default class MilSymbolSearch extends React.Component<
  IMilSymbolSearchProps,
  IMilSymbolSearchState
> {
  static defaultProps = {
    width: 280,
    iconSize: 40,
    cols: 5,
  };
  constructor(props: IMilSymbolSearchProps) {
    super(props);
    if (cookies.get("favSymbol") === undefined) {
      const defaultFavSymbols: IFavMainIcon[] = [];
      // @ts-ignore
      symbolDict.default.slice(0, 30).map((item) => {
        defaultFavSymbols.push({
          sidc: `${item.sidc.charAt(0)}${
            ["F", "H", "U"][Math.floor(Math.random() * 3)]
          }${item.sidc.substring(2)}`,
          label: item.nameZH,
          count: Math.floor(Math.random() * 500),
        });
      });

      cookies.set(
        "favSymbol",
        defaultFavSymbols.sort((a, b) =>
          a.count > b.count ? -1 : a.count === b.count ? 0 : 1
        ),
        { path: "/" }
      );
    }
    const favSymbols = cookies.get("favSymbol");
    favSymbols.map((item) => (item.svgDataURL = getSymbolBySidc(item.sidc)));
    this.state = {
      searchKeyword: "",
      mainIcons: favSymbols || [],
      currentSymbol:{}
    };
  }

  handleInputValue = (event: React.ChangeEvent<{}>, value: string) => {
    this.setState({ searchKeyword: value});
    if(value.length<1) {
      const favSymbols = cookies.get("favSymbol");
      favSymbols.map((item) => (item.svgDataURL = getSymbolBySidc(item.sidc)));
      this.setState({mainIcons:favSymbols});
    }else{
      this.setState({mainIcons: searchSymbols(value, false) });
    }
  };
  handleSearch = (event: React.ChangeEvent<{}>, value: any) => {
    const key = value as string; //typeof value === "string"? value as string :value.nameZH ;
    this.setState({ searchKeyword: key});
    if(key.length <1 ) return;
    this.setState({ mainIcons: searchSymbols(key, false) });
  };

  imgMouseOverHandle = (e) => {
    e.target.style.background = 'blue';
  };
  imgMouseOutHandle = (e,item) => {    
    const {currentSymbol} = this.state;
    // @ts-ignore
    e.target.style.background = item.sidc === currentSymbol.sidc ? 'blue': '';
  };

  render() {
    const { searchKeyword,mainIcons,currentSymbol} = this.state;
    const { width, iconSize, cols, onImgClick } = this.props;
    return (
      <React.Fragment>
        <div style={{ width: width, padding: 15 }}>
          <Autocomplete
            freeSolo
            id="free-solo-2-demo"
            style={{ padding: 15 }}
            disableClearable
            // @ts-ignore
            options={symbolDict.default.map((symbol) => symbol.nameZH)}
            renderInput={(params) => (
              <TextField
                {...params}
                label="点击选择或输入关键字"
                margin="normal"
                // variant="outlined"
                InputProps={{ ...params.InputProps, type: "search" }}
              />
            )}
            value={searchKeyword}
            inputValue={searchKeyword}
            onInputChange={this.handleInputValue}            
            onChange={this.handleSearch}
          />
        </div>
        {/* <ButtonGroup style={{ padding: 15 }}> */}
        <div style={{ padding: 15 }}>
          <Dialpad />
          <Typography style={{float:'right'}}>{searchKeyword.length === 0 ?'常用符号:':'搜索结果:'}{`${mainIcons.length} 个`}</Typography>
        </div>
        <Paper
          style={{ flexGrow: 1, maxWidth: `${width}px`, padding: 15 }}
        >
          <GridList
            style={{ width: width }}
            cellHeight={iconSize}
            spacing={8}
            cols={cols}
          >
            {mainIcons.map((item,index) => {
              // @ts-ignore
              const sidc = item.sidc;
              // @ts-ignore
              const label = item.label;
              // @ts-ignore
              const url = item.svgDataURL;
              return (
                <GridListTile key={`${sidc}${index}`}>
                  <Tooltip title={label}>                      
                    <img src={url} width={iconSize} height={iconSize} alt="" 
                    // @ts-ignore 
                    style={{background: item.sidc === currentSymbol.sidc?'blue':''}} onClick={(event) =>{this.setState({currentSymbol:item});onImgClick(event,item)}} onMouseOver={event=>this.imgMouseOverHandle(event)} onMouseOut={event=>this.imgMouseOutHandle(event,item)}/>
                  </Tooltip>
                </GridListTile>
              );
            })}
          </GridList>
        </Paper>
      </React.Fragment>
    );
  }
}


// getOptionLabel={(option) => {
//     console.log(option);
//     // @ts-ignore
//     return option.nameZH
// }}
// renderOption={(option) => (
//     <React.Fragment>
//         {
//         // @ts-ignore
//         <MilSymbol sidc={option.sidc}/>
//         }
//         {
//         // @ts-ignore
//         option.nameZH
//         }
//     </React.Fragment>
//   )}